﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Itfort;
using System.Data;
using MySoft.Data;
using System.Data.SqlTypes;
using MongoDB.Driver;
using MongoDB.Bson;
using System.Reflection;
using MongoDB.Driver.Builders;
namespace WanPiJie.Products
{
    public class ProductService : IProductService
    {
        private MongoCollection<BsonDocument> dbSession;

        public ProductService()
        {
            this.dbSession = MongoCollections.Wanpijie.GetCollection<BsonDocument>("pt_Product");
        }

        public long Count
        {
            get
            {
                return this.dbSession.Count();
            }
        }

        public void Insert(Product product)
        {
            this.dbSession.Insert(product.ToBsonDocument());
        }

        public Product GetProduct(Product product)
        {
            return this.GetProduct(this.GenerateQuery(product)).ToProduct();
        }

        /// <summary>
        /// 产生业务查询条件
        /// </summary>
        /// <param name="product">产品对象</param>
        /// <returns>以产品非空属性产生查询条件</returns>
        private IMongoQuery GenerateQuery(Product product)
        {
            string key;
            object value;
            var properties = typeof(Product).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            IList<IMongoQuery> queries = new List<IMongoQuery>();
            for (int i = 0; i < properties.Length; i++)
            {
                key = properties[i].Name;
                if (key.Equals("SerialNumber"))
                {
                    continue;
                }
                value = properties[i].GetValue(product, null);
                if (value != null)
                {
                    if (key.Equals("CatalogId"))
                    {
                        queries.Add(new QueryDocument(new Dictionary<string, object> { { key, value } }));
                    }
                    else
                    {
                        queries.Add(Query.EQ(string.Format("{0}.ValueSerialNumber", key), (value as ComplexAttributeValue).ValueSerialNumber));
                    }
                }
            }
            return Query.And(queries);
        }

        /// <summary>
        /// 获取单个销售信息
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>单个产品的Bson对象</returns>
        private BsonDocument GetProduct(IMongoQuery query)
        {
            return this.dbSession.FindOne(query);
        }

        public Product GetProduct(long serialNumber)
        {
            return this.GetProduct(Query.EQ("_id", serialNumber)).ToProduct();
        }
    }
}
